<template>
    <div class="common-layout">
        <el-container style="height: 100vh;">
            <!-- 头部 -->
            <el-header class="header">
                <div>学生宿舍管理系统</div>
                <!-- 下拉菜单 -->
                <!-- 头像 -->
                <div class="position">
                    <el-dropdown>
                        <span class="el-dropdown-link">
                            <div class="demo-type">
                                <div>
                                    <el-avatar> 陆 </el-avatar>
                                </div>
                            </div>
                            <el-icon class="el-icon--right"><arrow-down /></el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="a" @click="handleRegister">注销</el-dropdown-item>
                            </el-dropdown-menu>
                            <el-dropdown-menu>
                                <el-dropdown-item command="a" @click="handleChangePassword">修改密码</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </el-header>
            <el-container>
                <!-- 侧边栏 -->
                <el-aside class="aside">
                    <ul>
                        <li>
                            <router-link to="/index" class="a">首页</router-link>
                        </li>
                        <li>
                            <router-link to="/studentmanage" class="a">学生管理</router-link>
                        </li>
                        <li>
                            <router-link to="/dormitorymanage" class="a">宿舍管理</router-link>
                        </li>
                        <li>
                            <router-link to="/livemanage" class="a">入住管理</router-link>
                        </li>
                        <li>
                            <router-link to="/floormanage" class="a active">楼宇管理</router-link>
                        </li>
                    </ul>
                </el-aside>
                <el-container>
                    <!-- 主体部分 -->
                    <el-main style="background-color:#fff;text-align: center;">
                        <!-- 学生管理 -->
                        <div
                            style="border: 1px solid #fff;height: 70px;line-height: 70px; box-shadow: 1px 2px 10px #999;">
                            楼宇管理
                            <el-input v-model="buildingName" style="width: 240px;padding-left: 50px;"
                                placeholder="宿舍楼" />
                            <el-input v-model="managerName" style="width: 240px;padding-left: 50px;"
                                placeholder="管理员姓名" />
                            <el-button type="success" style="margin-left: 50px;" @click="search">
                                <el-icon>
                                    <Search />
                                </el-icon>
                                <span>查询</span>
                            </el-button>

                            <el-button type="primary" @click="addFloor = true;">
                                <el-icon>
                                    <CirclePlusFilled />
                                </el-icon>
                                <span>新增</span>
                            </el-button>
                            <!-- 添加数据弹框 -->
                            <el-dialog v-model="addFloor" title="添加楼宇数据" width="440">
                                <el-form :model="formadd">
                                    <el-form-item label="宿舍楼" :label-width="formaddWidth">
                                        <el-select v-model="formadd.buildingName" placeholder="请选择"
                                            style="width: 260px;">
                                            <el-option label="A栋" value="A栋" />
                                            <el-option label="B栋" value="B栋" />
                                            <el-option label="C栋" value="C栋" />
                                            <el-option label="D栋" value="D栋" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="地址" :label-width="formaddWidth">
                                        <el-input v-model="formadd.buildingAddress" autocomplete="off"
                                            style="width: 260px;" />
                                    </el-form-item>
                                    <el-form-item label="楼层数" :label-width="formaddWidth">
                                        <el-input v-model="formadd.floorCount" autocomplete="off"
                                            style="width: 260px;" />
                                    </el-form-item>
                                    <div style="margin:-20px 0 0 -39px;">
                                        <span style="margin-right: 15px;">建成时间</span>
                                        <el-date-picker style="width: 260px" v-model="startConstructionDate" type="date"
                                            placeholder="请选择建成日期" :default-value="new Date(2024, 9, 1)" />
                                    </div>
                                    <el-form-item label="建成状态" :label-width="formaddWidth">
                                        <el-select v-model="formadd.usageStatus" placeholder="请选择"
                                            style="width: 260px;">
                                            <el-option label="使用中" value="使用中" />
                                            <el-option label="维修中" value="维修中" />
                                            <el-option label="闲置" value="闲置" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="管理员" :label-width="formaddWidth">
                                        <el-input v-model="formadd.managerName" autocomplete="off"
                                            style="width: 260px;" />
                                    </el-form-item>
                                </el-form>
                                <template #footer>
                                    <div class="dialog-footer">
                                        <el-button @click="addFloor = false">取消</el-button>
                                        <el-button type="primary" @click="addFloorData">
                                            确认
                                        </el-button>
                                    </div>
                                </template>
                            </el-dialog>
                        </div>

                        <!-- 表格 -->
                        <div style="box-shadow: 1px 2px 10px #999;margin-top: 30px">
                            <el-table :data="floorData" border style="width: 100%;">
                                <el-table-column prop="id" label="序号" width="130" />
                                <el-table-column prop="buildingName" label="宿舍楼" width="200" />
                                <el-table-column prop="buildingAddress" label="地址" />
                                <el-table-column prop="floorCount" label="楼层数" width="130" />
                                <el-table-column prop="constructionDate" label="建成日期" width="130" />
                                <el-table-column prop="usageStatus" label="使用状态" width="130" />
                                <el-table-column prop="managerName" label="管理员" width="200" />
                                <el-table-column fixed="right" label="操作" width="130">
                                    <template #default="scope">
                                        <!-- scope.row.id获取id -->
                                        <el-button type="danger" :icon="Delete" circle plain
                                            @click="deleteFloor(scope.row.id)" />
                                        <el-button type="primary" :icon="Edit" circle plain
                                            @click="updates(scope.row.id)" />
                                    </template>
                                </el-table-column>
                            </el-table>
                            <!-- 编辑数据弹框 -->
                            <el-dialog v-model="updateFloor" title="编辑楼宇数据" width="440">
                                <el-form :model="formUpdate">
                                    <el-form-item label="宿舍楼" :label-width="formUpdateWidth">
                                        <el-select v-model="formUpdate.buildingName" placeholder="请选择"
                                            style="width: 260px;">
                                            <el-option label="A栋" value="A栋" />
                                            <el-option label="B栋" value="B栋" />
                                            <el-option label="C栋" value="C栋" />
                                            <el-option label="D栋" value="D栋" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="地址" :label-width="formUpdateWidth">
                                        <el-input v-model="formUpdate.buildingAddress" autocomplete="off"
                                            style="width: 260px;" />
                                    </el-form-item>
                                    <el-form-item label="楼层数" :label-width="formUpdateWidth">
                                        <el-input v-model="formUpdate.floorCount" autocomplete="off"
                                            style="width: 260px;" />
                                    </el-form-item>
                                    <div style="margin:0 0 16px -37px;">
                                        <span style="margin-right: 15px;">建成时间</span>
                                        <el-date-picker style="width: 260px" v-model="constructionDate" type="date"
                                            placeholder="请选择建成日期" :default-value="new Date(2024, 9, 1)" />
                                    </div>
                                    <el-form-item label="使用状态" :label-width="formUpdateWidth">
                                        <el-select v-model="formUpdate.usageStatus" placeholder="请选择"
                                            style="width: 260px;">
                                            <el-option label="使用中" value="使用中" />
                                            <el-option label="维修中" value="维修中" />
                                            <el-option label="闲置" value="闲置" />
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="管理员" :label-width="formUpdateWidth">
                                        <el-input v-model="formUpdate.managerName" autocomplete="off"
                                            style="width: 260px;" />
                                    </el-form-item>
                                </el-form>
                                <template #footer>
                                    <div class="dialog-footer">
                                        <el-button @click="updateFloor = false">取消</el-button>
                                        <el-button type="primary" @click="comfirmUpdate">
                                            确认
                                        </el-button>
                                    </div>
                                </template>
                            </el-dialog>
                        </div>
                    </el-main>
                    <!-- 版权 -->
                    <el-footer class="footer">
                        <span>© 2024 永恒帝宫. All rights reserved. </span>
                    </el-footer>
                </el-container>
            </el-container>
        </el-container>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { ArrowDown, Delete, Edit, Search } from '@element-plus/icons-vue'

const buildingName = ref('')
const managerName = ref('')

const router = useRouter() // 获取路由实例  
function handleRegister() {
    // 使用 setTimeout 延迟 1 秒后跳转到登录页面  
    setTimeout(() => {
        router.push('/login')
    }, 1000) // 延迟 1000 毫秒（1 秒）  
    ElMessage(`退出登录成功`)
}
function handleChangePassword() {
    router.push('/changepassword')
}

//后端返回楼的json数据，用数组接收
const floorData = ref([])
//发送异步请求，获取楼的数据
// 定义 fetchStudentData 函数以获取楼的数据
const fetchStudentData = async () => {
    try {
        const response = await axios.get('http://localhost:8080/selectFloorAll');
        floorData.value = response.data;
    } catch (error) {
        console.error("获取楼的数据失败: ", error);
    }
}
//在组件挂载时获取楼的数据
onMounted(async () => {
    await fetchStudentData();
});

//查询楼宇数据
const search = async () => {
    try {
        //封装数据给前端
        const floor = {
            "buildingName": buildingName.value,
            "managerName": managerName.value
        }
        const searchResponse = await axios.post('http://localhost:8080/getFloorByBuilName', floor);
        //把查询到的数据渲染到页面中
        floorData.value = searchResponse.data;
        //添加计数器，用于查询了多少条数据
        let count = 0;
        for (let i = 0; i < floorData.value.length; i++) {
            count++;
        }
        ElMessage({
            message: '查询成功，共查询了' + count + '条数据',
            type: 'success',
        })
    } catch {
        setTimeout(() => {
            ElMessage({
                message: '服务器未响应',
                type: 'warning'
            })
        }, 1000);
    }
}

//对日期的处理
function formatDate(date) {
    // 获取年、月、日
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
    const day = String(date.getDate()).padStart(2, '0');

    // 拼接成 yyyy-MM-dd 格式的字符串
    const formattedDate = `${year}-${month}-${day}`;
    return formattedDate;
}

//添加学生数据
const addFloor = ref(false)
const formaddWidth = '90px'
const startConstructionDate = ref('')
const formadd = reactive({
    buildingName: '',
    buildingAddress: '',
    floorCount: '',
    usageStatus: '',
    managerName: '',
})

const addFloorData = async () => {
    try {
        // 日期对象
        let flDate = '';
        if (startConstructionDate.value) {
            const floorDate = new Date(startConstructionDate.value);
            flDate = formatDate(floorDate);
        }

        //把学生数据封装到对象中
        const floorData = {
            "buildingName": formadd.buildingName,
            "buildingAddress": formadd.buildingAddress,
            "floorCount": formadd.floorCount,
            "constructionDate": flDate,
            "usageStatus": formadd.usageStatus,
            "managerName": formadd.managerName,
        }
        if (formadd.buildingName == '' || formadd.buildingAddress == ''
            || formadd.floorCount == '' || formadd.usageStatus == '' || formadd.managerName == '') {
            ElMessage({
                message: '请完善信息',
                type: 'warning',
                duration: 1000 // 设置消息显示时间为 1 秒
            })
            return;
        }
        //点击确认关闭弹窗
        addFloor.value = false;
        //发送数据给后端添加数据库
        await axios.post("http://localhost:8080/insertFloorData", floorData);
        //数据添加完初始化数据
        formadd.buildingName = '';
        formadd.buildingAddress = '';
        formadd.floorCount = '';
        startConstructionDate.value = '';
        formadd.usageStatus = '';
        formadd.managerName = '';
        //修改成功后更新学生页面数据
        await fetchStudentData();
        ElMessage({
            message: '添加成功',
            type: 'success',
            duration: 1000 // 设置消息显示时间为 1 秒
        })
    } catch {
        setTimeout(() => {
            ElMessage({
                message: '服务器未响应',
                type: 'warning'
            })
        }, 1000); // 过1秒弹出服务器未响应
    }
}

//删除楼的数据
const deleteFloor = (floorId) => {
    ElMessageBox.confirm(
        '你确认要删除吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //发送异步请求到后端,根据id删除学生信息~
            try {
                await axios.delete(`http://localhost:8080/deleteFloor/${floorId}`)
                // 成功删除后更新页面数据
                //保留所有 id 不等于 floorId 的楼层对象
                floorData.value = floorData.value.filter((floor: { id: number }) => floor.id !== floorId);
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                    duration: 1000 // 设置消息显示时间为 1 秒
                })
            } catch {
                setTimeout(() => {
                    ElMessage({
                        type: 'warning',
                        message: '服务器未响应',
                    })
                }, 1000); // 过1秒弹出服务器未响应
            }
        })
}

// 修改楼的数据
const updateFloor = ref(false)
const formUpdateWidth = '90px'
const stdID = ref();
const constructionDate = ref('');

const formUpdate = reactive({
    buildingName: '',
    buildingAddress: '',
    floorCount: '',
    usageStatus: '',
    managerName: ''
})

// 在 setup 函数中声明 floorDataList 的类型
const floorDataList = ref<{ id: number, buildingName: string, buildingAddress: string, floorCount: string, constructionDate: string, usageStatus: string, managerName: string }[]>([]);
const updates = async (floorId) => {
    //点击编辑按钮，弹出弹窗
    updateFloor.value = true;
    try {
        //根据传递id，后端返回相对应的值
        const floorData = await axios.get(`http://localhost:8080/getFloorById?id=${floorId}`)
        floorDataList.value = floorData.data
        //获取对应的id用于获取对应编辑内容，便于修改
        stdID.value = floorDataList.value[0].id;
        //把值给到编辑框中
        formUpdate.buildingName = floorDataList.value[0].buildingName;
        formUpdate.buildingAddress = floorDataList.value[0].buildingAddress;
        formUpdate.floorCount = floorDataList.value[0].floorCount;
        constructionDate.value = floorDataList.value[0].constructionDate;
        formUpdate.usageStatus = floorDataList.value[0].usageStatus;
        formUpdate.managerName = floorDataList.value[0].managerName;

    } catch {
        setTimeout(() => {
            ElMessage({
                message: '服务器未响应',
                type: 'warning'
            })
        }, 1000); // 过1秒弹出服务器未响应
    }
}


const comfirmUpdate = async () => {
    // 日期对象
    let flDate = '';
    if (constructionDate.value) {
        const floorDate = new Date(constructionDate.value);
        flDate = formatDate(floorDate);
    }
    //点击确认关闭弹窗
    updateFloor.value = false;
    //把楼宇数据封装到对象中
    const floorData = {
        "id": stdID.value,
        "buildingName": formUpdate.buildingName,
        "buildingAddress": formUpdate.buildingAddress,
        "floorCount": formUpdate.floorCount,
        "constructionDate": flDate,
        "usageStatus": formUpdate.usageStatus,
        "managerName": formUpdate.managerName
    }
    try {
        if (stdID.value == '' || formUpdate.buildingName == '' || formUpdate.buildingAddress == ''
            || formUpdate.floorCount == '' || formUpdate.usageStatus == '' || formUpdate.managerName == '') {
            ElMessage({
                message: '修改失败',
                type: 'error',
                duration: 1000 // 设置消息显示时间为 1 秒
            })
            return;
        }
        //把数据给到后端
        await axios.put("http://localhost:8080/updateFloor", floorData)

        //修改成功后更新楼宇页面数据
        await fetchStudentData();
        ElMessage({
            message: '修改成功',
            type: 'success',
            duration: 1000 // 设置消息显示时间为 1 秒
        })
    } catch {
        setTimeout(() => {
            ElMessage({
                message: '服务器未响应',
                type: 'warning'
            })
        }, 1000); // 过1秒弹出服务器未响应
    }
}
</script>

<style scoped>
body {
    background-color: transparent;
}

html,
body {
    /* 移除默认的边距和填充 */
    margin: 0;
    padding: 0;
    /* 确保页面高度至少与视口高度相同 */
    min-height: 100vh;
}


ul {
    margin: 0;
    padding: 0;
    text-align: center;
}

li {
    list-style: none;
}

.header {
    position: relative;
    background-color: #683b9e;
    font-size: 35px;
    height: 80px;
    line-height: 80px;
    color: #f9f1fa;
}

.aside {
    width: 200px;
    background-color: #8eb1c4;
}

ul li .a {
    height: 60px;
    line-height: 60px;
    display: block;
    text-decoration: none;
    font-size: 20px;
    width: 100%;
    color: black;
}

ul li .active {
    background-color: #044a8083;
    color: white;
}

ul li .a:hover {
    color: white;
}

.unlogin {
    text-decoration: none;
    color: #888;
}

.example-showcase .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}

.el-dropdown-link {
    position: relative;
    cursor: pointer;
    color: #fff
}

.el-dropdown-link div {
    display: inline-block;
    width: 40px;
    height: 40px;
}

.position {
    position: absolute;
    top: 23px;
    right: 30px;
}

.footer {
    margin: 0;
    padding: 0;
    height: 50px;
    line-height: 50px;
    text-align: center;
    background-color: rgba(9, 218, 176, 0.404);
    color: #fff;
    border: 0;
}
</style>